<template>
  <div class="register-container">
    <div class="register-form-wrapper">
      <h2 class="register-title">用户注册</h2>
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-width="100px" class="register-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input type="password" v-model="registerForm.pwd" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input type="password" v-model="registerForm.confirmPwd" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="registerForm.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="number" v-model="registerForm.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="stuNum">
          <el-input v-model="registerForm.stuNum" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="registerForm.className" placeholder="请输入班级名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" class="register-btn">注册</el-button>
          <el-button @click="goToLogin" class="login-btn">返回登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { userAPI } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'RegisterView',
  data() {
    return {
      registerForm: {
        username: '',
        pwd: '',
        confirmPwd: '',
        realName: '',
        age: 18,
        email: '',
        stuNum: '',
        className: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPwd: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.registerForm.pwd) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { type: 'number', min: 1, max: 150, message: '年龄在 1 到 150 之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        stuNum: [
          { required: true, message: '请输入学号', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '请输入班级名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async handleRegister() {
      try {
        this.$refs.registerForm.validate(async (valid) => {
          if (valid) {
            // 向后端发送所有需要的字段
            const userData = {
              username: this.registerForm.username,
              pwd: this.registerForm.pwd,
              realName: this.registerForm.realName,
              age: this.registerForm.age,
              email: this.registerForm.email,
              stuNum: this.registerForm.stuNum,
              className: this.registerForm.className
            }
            
            const response = await userAPI.register(userData)
            
            // 检查响应中的errno字段判断注册是否成功
            if (response && response.errno === 0) {
              // 注册成功，创建一个标准格式的用户信息对象
              const newUserInfo = {
                id: response.insertId || Math.floor(Math.random() * 1000) + 100,
                userId: response.insertId || Math.floor(Math.random() * 1000) + 100,
                username: userData.username,
                realName: this.registerForm.realName,
                role: 'student'
              }
              
              // 存储基本的用户信息，方便后续登录使用
              try {
                localStorage.setItem('userInfo', JSON.stringify(newUserInfo))
              } catch (jsonError) {
                console.error('存储用户信息错误:', jsonError)
              }
              
              ElMessage.success('注册成功，请登录')
              this.$router.push('/login')
            } else {
              // 注册失败，显示错误信息
              ElMessage.error(response?.message || '注册失败，请稍后重试')
            }
          }
        })
      } catch (error) {
        console.error('注册错误:', error)
        ElMessage.error('注册失败，请稍后重试')
      }
    },
    goToLogin() {
      this.$router.push('/login')
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  background-image: 
    radial-gradient(#67c23a 1px, transparent 1px),
    radial-gradient(#67c23a 1px, transparent 1px);
  background-size: 40px 40px;
  background-position: 0 0, 20px 20px;
  background-attachment: fixed;
}

.register-form-wrapper {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 40px;
  width: 100%;
  max-width: 500px;
  position: relative;
  overflow: hidden;
}

.register-form-wrapper::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #67c23a, #409eff);
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.register-form {
  margin-top: 20px;
}

.register-btn {
  width: 45%;
  margin-right: 5%;
}

.login-btn {
  width: 45%;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-form-wrapper {
    padding: 20px;
    margin: 20px;
  }
  
  .register-title {
    font-size: 20px;
  }
  
  .register-btn,
  .login-btn {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  

}
</style>